﻿Tags = {
    split: function(val) {
        return val.split(/,\s*/);
    },
    extractLast: function(term) {
        return Tags.split(term).pop();
    },
    autoCompleteTextbox: function(control, href) {
        control
        .autocomplete({
            source: function(request, response) {
                // delegate back to autocomplete, but extract the last term
                var lastTerm = Tags.extractLast(request.term);
                var hrefTarget = href + "&keyword=" + lastTerm;

                $.get(hrefTarget, function(data) {
                    try {
                        if (data != '{|noresult|}') {
                            var arr = Tags.split(data);
                            response($.ui.autocomplete.filter(arr, lastTerm));
                        }
                    }
                    catch (err) {
                    }
                });
            }
        });
    },
    autoCompleteTextboxMultiValue: function(control, href) {
        control
        .bind("keydown", function(event) {
            if (event.keyCode === $.ui.keyCode.TAB &&
						        $(this).data("autocomplete").menu.active) {
                event.preventDefault();
            }
        })
        .autocomplete({
            minLength: 0,
            source: function(request, response) {
                // delegate back to autocomplete, but extract the last term
                var lastTerm = Tags.extractLast(request.term);
                var hrefTarget = href + "&keyword=" + lastTerm;

                $.get(href, function(data) {
                    try {
                        if (data != '{|noresult|}') {
                            var arr = Tags.split(data);
                            response($.ui.autocomplete.filter(arr, lastTerm));
                        }
                    }
                    catch (err) {
                    }
                });
            },
            focus: function() {
                // prevent value inserted on focus
                return false;
            },
            select: function(event, ui) {
                var terms = Tags.split(this.value);
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push(ui.item.value);
                // add placeholder to get the comma-and-space at the end
                terms.push("");
                this.value = terms.join(", ");
                return false;
            }
        });
    },
    hideTag: function(ctl, hdTagsName) {
        var title = $(ctl).attr("title");
        var newval = $('#' + hdTagsName).val().replace(title, "");
        $('#' + hdTagsName).val(newval);
        $(ctl).parent().remove();
    }
}